package com.briup.shopadmin.service.impl;

import com.briup.shopadmin.common.GlobalException;
import com.briup.shopadmin.common.bean.Category;
import com.briup.shopadmin.common.vo.CategoryVO;
import com.briup.shopadmin.dao.ICategoryDao;
import com.briup.shopadmin.service.ICategoryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
public class CategoryServiceImpl implements ICategoryService {
    @Autowired
    ICategoryDao categoryDao;

    @Override
    public List<CategoryVO> findAll() {
        ArrayList<CategoryVO> categoryVOS = new ArrayList<>();
//        查询一级分类
        List<Category> list = categoryDao.findByParentIdIsNull();
        for (Category category : list) {
//            每有一个一级分类就意味着有一个vo对象
            CategoryVO vo = new CategoryVO(category);
//            根据以一级分类的id、查询对应的二级分类
            List<Category> categories = categoryDao.findByParentId(vo.getId());
            vo.setCategories(categories);
            categoryVOS.add(vo);
        }
        return categoryVOS;

    }

    @Override
    public List<Category> findCategorysOneLevel() {
        return categoryDao.findByParentIdIsNull();
    }

    @Override
    public List<Category> findCategoryByOneLevel(Long id) {
        return categoryDao.findByParentId(id);
    }

    @Override
    public void save(Category category) {
        categoryDao.save(category);
    }

    @Override
    public void findByName(String name) {
        Category category = categoryDao.findByName(name);
        if (category!=null){
            throw new GlobalException(53001,"分类名称已经存在");
        }

    }

    @Override
    public void deleteById(long id) {
        categoryDao.deleteById(id);
    }
}
